var st;
var userinfo = null;

function login () {
  toast('数据加载中...');
  nebPay.simulateCall(dappAddress, "0", "login", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      
      var info = JSON.parse(res.result);
      if (!info) {
        toast('您尚未注册,系统正在自动注册中...');
        register()
      } else {
        toast('您已注册过,自动登录中...')
        userinfo = JSON.parse(info);
        renderHTml();
      }

    }
  })
}

function register () {
  nebPay.call(dappAddress, "0", "register", JSON.stringify([]), { 
    listener: function(res) {
      initTime = Date.now();
      toast(res.txhash ? '注册成功。' : '注册失败.请刷新页面重试！！！');
      userinfo = {
        address: address,
        balance: '0',
        email: [{
          id: "morenyoujianmorenID",
          addressor: "n1X7NJbKyVz5wAsvaupBYt52fS76d38sStc",
          recipient: address,
          title: "欢迎使用星云邮箱",
          text: "星云邮箱是一款基于星云链的去中心化邮箱服务平台。相比较于传统邮箱,星云邮箱每收一件(除本邮件外)用户会得到0.05nas。每发一件相应会收手续0.05nas作为保证用户不是对目标用户发起垃圾邮件轰炸和广告邮件...看信发送交易是因为要存储看信记录",
          date: Date.now(),
          type: 0 // 0 为读 1已读
        }],
        send: []
      }
      renderHTml()
    }
  })
}

var unreadDate = [];

function unreadNum () {
  if (!userinfo || !userinfo.email) {
    return false
  }
  unreadDate = [];
  var num = 0;
  for (var i = 0; i < userinfo.email.length; i++) {
    if (!userinfo.email[i].type) {
      num++;
      unreadDate.push(userinfo.email[i]);
    }
  }

  return num
}

$('#collection').on('click', function () {
  var emailArr = userinfo.email;
  collectionFn(emailArr);
})

$('#unread').on('click', function () {
  collectionFn(unreadDate);
})

$('#send-menu').on('click', function () {
  collectionFn(userinfo.send);
})

function collectionFn (data) {
  var html = '';
  if (data.length) {
    for (var i = 0; i < data.length; i++) {
      html += '<li data-id="'+data[i].id+'">'
        +'<div class="user">'+data[i].addressor+'</div>'
        +'<div class="name">'+data[i].title+'</div>'
        +'<div class="date">'+getTime(data[i].date)+'</div>'
      +'</li>'
    }
  } else {
    html += '暂无邮件'
  }
  $('.email-list ul').html(html)
}

function renderHTml () {
  $('#unread-num').html(unreadNum());
  $('#collection-num').html(userinfo.email.length);
  $('#balance').html(userinfo.balance);
  var emailArr = userinfo.email;
  collectionFn(emailArr);
}


$('body').on('click', '.email-list li', function () {
  var id = $(this).data('id');
  var email = null
  for (var i = 0; i < userinfo.email.length; i++) {
    if (userinfo.email[i].id == id) {
      userinfo.email[i].type = 1;
      email = userinfo.email[i];
    }
  }

  $('#unread-num').html(unreadNum());
  
  $('#message-fa').html(email.addressor);
  $('#message-shou').html(email.recipient);
  $('#message-date').html(getTime(email.date));
  $('#message-text').html(email.text);
  $('#email-email').addClass('open-email');
  $('#reply').data('add', email.addressor);
  readMail(id);
})

function readMail (id) {
  nebPay.call(dappAddress, "0", "readMail", JSON.stringify([id]), { 
    listener: function(res) {
      if (res.result == '' && res.execute_err == 'contract check failed') {
        toast('区块链储存看信记录失败!!,请刷新浏览器!');
      }
    }
  })
}

$('#forward').on('click', function () {
  if (userinfo.balance == 0) {
    toast('没有足够的余额');
    return false;
  }
  nebPay.call(dappAddress, "0", "takeout", JSON.stringify([]), { 
    listener: function(res) {
      toast(res.txhash ? '提现成功' : '提现失败.请刷新页面重试！！！');
      userinfo.balance = 0;
      $('#balance').html(0)
      renderHTml();
    }
  })
})

$('#send').on('click', function () {
  // 发件
  var addressee = $('#addressee').val();
  var theme = $('#theme').val();
  var textarea = $('textarea').val();
  var id = Date.now() +'_'+ ~~(Math.random() * 1e6);
  if (addressee && theme && textarea) {
    // 区块链发件
    var data = {
      id: id,
      addressor: addressee,
      recipient: address,
      title: theme,
      text: textarea,
      date: Date.now()
    }

    nebPay.call(dappAddress, "0", "send", JSON.stringify([data]), { 
      listener: function(res) {
        toast(res.txhash ? '发信成功' : '提现失败.请刷新页面重试！！！');
        data.type = 1;
        userinfo.send.unshift(data);
      }
    })
  }
})